package com.sunyard.pcc.web.controller;

import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;

/**
 * @Author: Hewei
 * @Description: 验证码生成controller
 * @Date: Created in 14:34 2018/2/22
 */
@Controller
public class VerificationCodeController {

    @Autowired
    private Producer producer;

    @PostMapping(value = "captcha.jpg")
    public void getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception{
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");


        //生成验证码文字
        String text = producer.createText();
        //生成验证码图片
        BufferedImage image = producer.createImage(text);
        // TODO: 2018/2/22 将验证码缓存入Session中
//        HttpSession session = request.getSession();
//        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, text);
        //输出至前端
        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(image, "jpg", outputStream);
        outputStream.close();
    }

}
